using System;
using System.Web;
using System.Web.Routing;

namespace Limestone.MVC
{
    public class HandledPagePathConstraint : IRouteConstraint
    {
        private readonly IPageProvider _pageProvider;
        private readonly string _handledTemplatePath;

        public HandledPagePathConstraint(IPageProvider pageProvider,string handledTemplatePath)
        {
            _pageProvider = pageProvider;
            _handledTemplatePath = handledTemplatePath.StartsWith("/") ? handledTemplatePath : "/" + handledTemplatePath;
        }

        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            var pagePath = values[parameterName] as string;
            if (string.IsNullOrEmpty(pagePath))
            {
                pagePath = "/";
            }

            var page = _pageProvider.Get(pagePath);

            return page != null && (page.TemplatePath.Equals(_handledTemplatePath, StringComparison.InvariantCultureIgnoreCase));
        }
    }
}